package com.geek.javase.ch10.work.setwork.work2;

import java.util.HashSet;
import java.util.Objects;

/*
 *@author wangpeng
 *2025/10/21 16:36
 *@description TODO
 */
//练习2.定义一个Person数组，将Person数组中的重复对象剔除   ===》不允许重复存放元素,Person重写equals()和hashCode()

public class Demo2 {
    public static void main(String[] args) {
        HashSet<Person> set = new HashSet<Person>();
        Person p1 = new Person("zhangsan", 18);
        Person p2 = new Person("lisi", 19);
        Person p3 = new Person("wangwu", 18);
        Person p4 = new Person("zhangsan", 18);

        set.add(p1);
        set.add(p2);
        set.add(p3);
        set.add(p4);
        System.out.println(set);

    }

}
class Person{
    private String name;
    private int age;

    //重写equals和hashCode
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Person{name = " + name + ", age = " + age + "}";
    }
}